package a08_回溯算法;

import java.util.*;

/**
 * <p>
 * a16_全排列2复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/2/27
 */
public class a16_全排列2复习2 {

    public static void main(String[] args) {
        a16_全排列2复习2 test = new a16_全排列2复习2();
        System.out.println(test.permuteUnique(new int[]{1, 1, 2}));
    }

    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        boolean[] used = new boolean[nums.length];
        traversal(result, path,used, nums);
        return result;
    }

    private void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           boolean[] used,
                           int[] nums){

        if(path.size() == nums.length){
            result.add(new ArrayList<>(path));
            return;
        }

        Set<Integer> set = new HashSet<>();//横向去重
        for (int i = 0; i < nums.length; i++) {
            if(set.contains(nums[i]) || used[i]){
                continue;
            }
            set.add(nums[i]);
            path.add(nums[i]);
            used[i] = true;
            traversal(result, path,used,nums);
            path.removeLast();
            used[i] = false;
        }
    }
}
